package utils

import (
	"JudgeClient/global"
	"bytes"
	"crypto/md5"
	"encoding/hex"
	"fmt"
	"os"
	"strings"
)

func GetFileNames(dirPth string, suffix string) (files []string, err error) {
	files = make([]string, 0, 10)
	dir, err := os.ReadDir(dirPth)
	if err != nil {
		return nil, err
	}

	for _, fi := range dir {
		if fi.IsDir() {
			continue
		}
		if strings.HasSuffix(fi.Name(), suffix) {
			files = append(files, strings.TrimSuffix(fi.Name(), suffix))
		}
	}
	return files, nil
}

func CheckToken(token string) bool {
	hash := md5.Sum([]byte(token))
	if hex.EncodeToString(hash[:]) != global.Conf.Server.Token {
		return false
	}
	return true
}

func compareOutput(testOutFilePath string, runOutFilePath string) (outputMd5 string, res bool) {
	testOut, _ := os.ReadFile(testOutFilePath)
	// Linux files has a line break at the end defaultly,trim it!
	trimed := bytes.TrimRight(testOut, "\n")
	testMD5 := md5.Sum(trimed)
	userOut, _ := os.ReadFile(runOutFilePath)
	trimed = bytes.TrimRight(userOut, "\n")
	userMD5 := md5.Sum(trimed)
	outputMd5 = fmt.Sprintf("%x", userMD5)
	res = bool(testMD5 == userMD5)
	defer os.Remove(runOutFilePath)
	return
}
